const request = require('request');
const config = require('../db/config');
const log4js      = require('../utils/logUtils');
const logger      = log4js.getLogger('service');
const TAG = "[外部接口] [获取拉流地址]";
/**
 * 登陆API接口
 */
async function login(){
    return new Promise(function (resolve, reject) {
        request({
            url: config.proxyApi.host + config.proxyApi.login,
            method: 'POST',
            json: true,
            headers: {
                "content-type": "application/json",
            }
        }, function (error, response, body) {
            if (error) {
                reject(error);
            } else {
                resolve(body.data.userinfo.token);
            }
        });
    });

}

/**
 * 从服务器获取摄像头信息列表
 */
async function getCameras(token){
    const offset=0;
    const limit = config.proxyApi.pageSize;
    const sort = "channels.last_check_time";
    const order = "asc";

    return new Promise(function (resolve, reject) {
        const options = {
            url: config.proxyApi.host + config.proxyApi.cameraList + '?token=' + token + '&offset='
                + offset + "&limit=" + limit + "&sort=" + sort + "&order=" + order
        };
        request.get(options, function (err, response, body) {
            if (err) {
                logger.error(TAG, 'request channels error', err);
                reject(err);
            } else {
                // console.info('request cameras body', body);
                resolve(JSON.parse(body).data.rows);
            }
        });
    });

}


module.exports = {login,getCameras};
